package com.mzj.saas.mservice.sys.service;

import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.sys.entity.WechatAccount;
import com.mzj.saas.mservice.sys.repository.WechatAccountRepository;
import com.mzj.saas.mservice.sys.vo.WechatAccountVO;
import com.mzj.saas.redis.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;


@Service
public class WechatAccountService {
    private Logger LOG = LoggerFactory.getLogger(WechatAccountService.class);
    @Autowired
    private RedisService redisService;
    @Autowired
    private WechatAccountRepository wechatAccountRepository;

    /*
     *商户号信息显示
     */
    public ResultBean<Object> showInfo(String accessToken) {
        LOG.info("---WechatAccountService showInfo accessToken={}", accessToken);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            List<WechatAccount> wechatAccountList = wechatAccountRepository.findByOrgId(tokenRedisVo.getEnterpriseId());
            result.setResultData(wechatAccountList);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     *商户号新增/修改
     */
    public ResultBean<Object> addOrUpdateInfo(String accessToken, WechatAccountVO wechatAccountVO, MultipartFile file) {
        LOG.info("---WechatAccountService addOrUpdateInfo accessToken={},wechatAccountVO={},file={}", accessToken, wechatAccountVO, file);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            if (wechatAccountVO == null) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            if(wechatAccountVO.getType().intValue()==1) {
                /*if (wechatAccountVO.getMchPublicPem() == null) {
                    return ResultBean.failedResultWithMsg("APPSECRET不能为空");
                }*/
                if (wechatAccountVO.getMchApiKey() == null) {
                    return ResultBean.failedResultWithMsg("API秘钥不能为空");
                }
                
                /*if(wechatAccountVO.getMchCertificate() == null || wechatAccountVO.getMchCertificate().length <= 0){
                	return ResultBean.failedResultWithMsg("微信API证书不能为空");
                }*/
            }
            if (wechatAccountVO.getMchId() == null) {
                return ResultBean.failedResultWithMsg("商户号不能为空");
            }
            if (wechatAccountVO.getType()== null) {
                return ResultBean.failedResultWithMsg("类型不能为空");
            }
            if (file != null) {
                byte[] mchCertificate = this.inputStreamToByte(file.getInputStream());
                wechatAccountVO.setMchCertificate(mchCertificate);
            }

            WechatAccount wechatAccount = new WechatAccount();
            if (wechatAccountVO.getId()==null){
                wechatAccountVO.setOrgId(tokenRedisVo.getEnterpriseId());
                wechatAccountVO.setCreatorId(tokenRedisVo.getId());
                wechatAccountVO.setCreateTime(new Date());
                BeanUtils.copyProperties(wechatAccountVO, wechatAccount);
            }else{
                WechatAccount existWechatAccount = wechatAccountRepository.findById(wechatAccountVO.getId()).get();
                if(wechatAccountVO.getType().intValue()==1) {  //微信
                    existWechatAccount.setMchId(wechatAccountVO.getMchId());
                    existWechatAccount.setMchApiKey(wechatAccountVO.getMchApiKey());
                    //existWechatAccount.setMchPublicPem(wechatAccountVO.getMchPublicPem());
                    if (wechatAccountVO.getMchCertificate() != null) {
                        existWechatAccount.setMchCertificate(wechatAccountVO.getMchCertificate());
                    }
                }else{

                    existWechatAccount.setMchId(wechatAccountVO.getMchId());
                    existWechatAccount.setPublicKey(wechatAccountVO.getPublicKey());
                    existWechatAccount.setPrivateKey(wechatAccountVO.getPrivateKey());

                }
                BeanUtils.copyProperties(existWechatAccount, wechatAccount);
            }
            wechatAccount.setLastUpdateTime(new Date());
            wechatAccountRepository.save(wechatAccount);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    private byte[] inputStreamToByte(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int length;
        while ((length = inputStream.read()) != -1) {
            outputStream.write(length);
        }
        byte data[] = outputStream.toByteArray();
        outputStream.close();

        return data;
    }
}
